// pages/activeDetail/activeDetail.js
var app=getApp();
var fileFunc = require('../../utils/main.js');
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    imageUrl: app.globalData.imageUrl,
    userId: '',
    userInfo:'',
    isThumbsUp:false,//是否点赞
    imgUrls:[],
    current:1,
    indicator:false,
    isMine:false,
    type:null,
    actiItem:'',
    typeTxt:"",
    showDel:true,
    currentId:'',
    followName:'关注',
    signName:'报名',
    isFollow: false,
    isSign: false,
    joinInfo:'',
    page: '',
    joinNum: 0,
    loadSuccess: false
  },
  // 根据id获取已参与人数
  joinNumFunc: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivityJoin/getCountsByActivityId',
      data: { activityId: _this.data.currentId },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        _this.setData({
          joinNum: res.data.data
        })
      }
    })
  },
  // 查询参与人员
  getPartner: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivityJoin/getJoinUserByActivityId',
      data: { activityId: _this.data.currentId },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if(res.data.success){
          _this.setData({
            joinInfo: res.data.data
          })
        }
      }
    })
  },
  // 根据id获取活动详情
  getDetailInfo:function(){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivity/getActivityDetailsById',
      data: { userId: _this.data.userId, id: _this.data.currentId },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        _this.setData({
          loadSuccess: true,
          actiItem: res.data.data,
          isThumbsUp: res.data.data.likeCount,
          isFollow: res.data.data.attentionCount,
          isSign: res.data.data.joinCount,
          imgUrls: res.data.data.activityImgUrl.split(",")
        })
        wx.hideLoading()
        if (res.data.data.attentionCount) {
          _this.setData({
            followName: '已关注'
          })
        }
        if (res.data.data.joinCount) {
          _this.setData({
            signName: '已报名'
          })
        }
        var jointString2 = "actiItem.releaseTime";
        _this.setData({
            [jointString2]: util.formatTime(_this.data.actiItem.releaseTime)
        })

      }
    })
  },
  // 打电话
  toggleSelect: function (e) {
    var show = e.currentTarget.dataset.value == "true" ? true : false;
    this.setData({
      showSelect: show,
      current_tel: e.currentTarget.dataset.tel
    })
  },
  callPhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.value
    })
    this.setData({
      showSelect: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    var id = options.id;
    if (options.page != undefined){
      this.setData({
        page: '/pages/' + options.page + '/' + options.page
      })
    }
    this.setData({
      currentId: id,
      userId: JSON.parse(wx.getStorageSync('userInfo')).id,
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })
    var obj = { '1': '【兴趣交流】', '2': '【知识讲座】', '3': '【交友相亲】', '4':'【亲子互动】'}
    if (options.isMine){
      if (options.type=='2'){
        this.setData({
          showDel: false
        })
      }
      this.setData({
        isMine:true,
        type: parseInt(options.type),//1 我的关注  2我的发布  3我的报名
      })
    }
    this.getDetailInfo();
    this.addbrowse();
    this.getPartner();
    this.joinNumFunc();
    wx.showLoading()
  },
  intervalChange: function (e) {
    this.setData({
      current: e.detail.current+1
    })
  },
  delBtn:function(e){//删除按钮点击事件
    if (this.data.type == 1) {//取消我的关注
      this.onFollowFunc('1');
    } else if (this.data.type == 2) {//取消我的发布

    } else if (this.data.type == 3) {//取消我的报名
      this.onSignFunc('1');
    }
  },
  // 添加浏览记录
  addbrowse: function () {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivityBrowse/save',
      data: {activityId: _this.data.currentId },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
      }
    })
  },
  thumbsUp:function(e){//点赞
    var _this = this;
    let thumbsUpNum = 'actiItem.likeCounts';
    if (this.data.isThumbsUp==true){
      wx.request({
        url: app.globalData.httpApiCar + 'tGyLike/deleteLikeRecordByParams',
        data: { userId: _this.data.userId, sourceId: _this.data.currentId, block: 1 },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            _this.setData({
              isThumbsUp: false,
              [thumbsUpNum]: _this.data.actiItem.likeCounts - 1
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }else{
      wx.request({
        url: app.globalData.httpApiCar + 'tGyLike/save',
        data: { userId: _this.data.userId, sourceId: _this.data.currentId, block: 1 },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success){
            _this.setData({
              isThumbsUp: true,
              [thumbsUpNum]: _this.data.actiItem.likeCounts + 1
            })
          }    
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }    
        }
      })
    }
  },
  // 分享
  share: function(){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivityShare/save',
      data: { userId: _this.data.userId, activityId: _this.data.currentId },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          _this.setData({
            ['actiItem.shareNums']: _this.data.actiItem.shareNums + 1
          })
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  enterPerson: function (e) {
    wx.navigateTo({
      url: '/pages/personalProfile/personalProfile?id=' + e.currentTarget.dataset.userid
    })
  },
  onShareAppMessage: function (res) {
    let _this = this;
    let shareNum = 'actiItem.likeCounts';
    return {
      title: '活动详情',
      path: '/pages/activeDetail/activeDetail',
      success: function (res) {
        _this.share()
        // 转发成功
      },
      fail: function (res) {
        this.setData({
          shareNum: this.data.shareNum + 1
        })
        // 转发失败
      }
    }
  },
  // 关注/取消关注
  onFollowFunc: function(flag){
    let _this = this;
    if(_this.data.isFollow){
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/deleteAttentionRecordByParams',
        data: { userId: _this.data.userId, sourceId: _this.data.currentId, block: 2 },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            if (flag == 1){
              _this.setData({
                showDel:false
              })
              wx.navigateBack()
            }
            _this.setData({
              isFollow: false,
              followName: '关注'
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
    else{
      wx.request({
        url: app.globalData.httpApiCar + 'tGyAttention/save',
        data: { userId: _this.data.userId, sourceId: _this.data.currentId, block: 2 },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if (res.data.success) {
            wx.showToast({
              title: '关注成功',
              icon: 'success',
              duration: 2000
            })
            _this.setData({
              isFollow: true,
              followName: '已关注'
            })
          }
          else {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    }
  },
  // 报名/取消报名
  onSignFunc: function (e,flag) {
    let _this = this;
    if (_this.data.isSign) {
     
    }
    else {
      let item = e.currentTarget.dataset.item;
      var index = e.currentTarget.dataset.index;
      var status = e.currentTarget.dataset.status;
      if (item.fee > 0) {
        this.payMoney(item)
      }
      else {
        this.enroll(item.id);
      }
    }
  },
  payMoney: function (item) {
    var that = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivity/payActivityFee',
      data: {
        orderId: item.id,
        openId: app.globalData.openId,
        userId: this.data.userInfo.id,
        money: item.fee,
        body: '活动报名费用'
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          that.requestPayment(res.data.data, item.id);
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  requestPayment: function (obj, id) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        that.enroll(id)
      },
      'fail': function (res) {
        wx.showModal({
          title: '提示',
          content: '支付失败',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              
            }
          }
        })
      }
    })
  },
  enroll: function (id) {
    let _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'tGyActivityJoin/joinActivity',
      data: { userId: _this.data.userId, activityId: id },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          wx.showToast({
            title: '报名成功',
            icon: 'success',
            duration: 2000
          })
          _this.data.actiItem[index][status] = true;
          _this.setData({
            actiItem: _this.data.actiItem
          })
        }
        else {
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})